<template>
  <div class="app-container">
    <!-- 患者信息搜索开始 -->
    <el-card class="box-card">
      <el-form ref="queryForm" :model="patientParams" :rules="rules" label-width="80px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input
                  v-model="patientParams.idCard"
                  placeholder="请输入患者身份证号"
                  clearable
                  size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleIdCardQuery">加载身份证号</el-button>
              <el-button type="warning" icon="el-icon-search" size="mini" @click="handleFullPatientInfo">加载患者信息</el-button>
              <el-button type="danger" icon="el-icon-refresh" size="mini" @click="resetPatientParam">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <!-- 患者基本信息表单开始 -->
    <el-card class="box-card">
      <el-form ref="form" :model="patientParams" :rules="rules" :inline="true" label-width="88px">
        <el-form-item label="身份证号">
          <el-input
              v-model="patientParams.idCard"
              placeholder="请输入身份证号"
              clearable
              size="small"
              style="width:200px"/>
        </el-form-item>
        <el-form-item label="患者姓名" prop="name">
          <el-input
              v-model="patientParams.name"
              placeholder="请输入患者姓名"
              clearable
              size="small"
              style="width:200px"/>
        </el-form-item>
        <el-form-item label="患者电话" prop="phone">
          <el-input
              v-model="patientParams.phone"
              placeholder="请输入患者电话"
              clearable
              size="small"
              style="width:200px"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="patientParams.sex">
            <el-radio
                v-for="d in sexOptions"
                :key="d.dictValue"
                :label="d.dictValue"
                :value="d.dictValue">{{ d.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
              v-model="patientParams.birthday"
              size="small"
              style="width:200px"
              value-format="yyyy-MM-dd"
              type="date"/>
        </el-form-item>
        <el-form-item label="患者年龄" prop="age">
          <el-input
              v-model="patientParams.age"
              readonly
              placeholder="请输入患者年龄"
              clearable
              size="small"
              style="width:200px"/>
        </el-form-item>
        <el-form-item label="地址信息" prop="address">
          <el-input
              v-model="patientParams.address"
              placeholder="请输入地址信息"
              clearable
              style="width:500px"
              size="small"/>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 患者基本信息表单结束 -->

    <el-card class="box-card">
      <el-row>
        <el-col :span="12">
          <el-radio-group v-model="queryDeptParams.regItemId" @change="registeredItemChange">
            <el-radio-button
                v-for="d in regItemOptions"
                :key="d.regItemId"
                :label="d.regItemId"
                :value="d.regItemId">{{ d.regItemName }}
            </el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col :span="12">
          <div style="float:right">
        <span style="margin-left:20px;font-weight: bold;font-size: 14px">
          挂号费:￥{{ queryDeptParams.regItemAmount }}&nbsp;&nbsp;
        </span>
            <el-button
                type="danger"
                icon="el-icon-search"
                :disabled="single || !queryDeptParams.regItemId || !isPatientLoaded"
                size="small"
                @click="handleRegistration">
              挂号收费
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>


    <el-card>
      <el-form ref="queryDeptForm" :model="queryDeptParams" :inline="true" label-width="68px">
        <el-form-item label="所属科室" prop="deptId">
          <el-select
              v-model="queryDeptParams.deptId"
              placeholder="请选择所属科室"
              clearable
              size="small"
              style="width:200px">
            <el-option
                v-for="d in deptOptions"
                :key="d.deptId"
                :label="d.deptName"
                :value="d.deptId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="挂号类型" prop="schedulingType">
          <el-select
              v-model="queryDeptParams.schedulingType"
              placeholder="请选择挂号类型"
              clearable
              size="small"
              style="width:200px">
            <el-option
                v-for="dict in schedulingTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="挂号时段" prop="subsectionType">
          <el-select
              v-model="queryDeptParams.subsectionType"
              placeholder="请选择挂号时段"
              clearable
              size="small"
              style="width:200px">
            <el-option
                v-for="dict in subsectionTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="挂号时间" prop="schedulingDay">
          <el-date-picker
              v-model="queryDeptParams.schedulingDay"
              size="small"
              style="width:240px"
              value-format="yyyy-MM-dd"
              type="date"
              :disabled-date="disablePastDates"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDeptQuery" >搜索</el-button>
          <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 部门数据表格开始 -->
      <el-table v-loading="loading" border :data="deptTableList" highlight-current-row
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="科室ID" align="center" prop="deptId"/>
        <el-table-column label="科室名称" align="center" :formatter="deptFormatter" prop="deptName"/>
        <el-table-column label="当前号数" align="center" prop="currentNumber"/>
      </el-table>
      <!-- 部门数据表格结束 -->
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Registered",
  data() {
    return {
      deptTableList: [],
      isPatientLoaded: false,
      userList: [],
      subsectionTypeOptions: [],
      deptOptions: [],
      schedulingTypeOptions: [],
      queryDeptParams: {
        regItemId: 1,
        regItemAmount: 0,
        deptId: null,
        schedulingType: 1,
        subsectionType: null,
        schedulingDay: null
      },
      regItemOptions: [],
      single: false,
      loading: false,
      patientParams: {
        idCard: "",
        name: "",
        phone: "",
        sex: "",
        birthday: "",
        age: "",
        address: "",
        isFinal:"0"
      },
      rules: {
        name: [{ required: true, message: '患者姓名不能为空', trigger: 'blur' }],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3|4|5|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '身份证号不能为空', trigger: 'blur' },
          { pattern: /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0[1-9])|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}X)$)$/, message: '请输入有效的身份证号', trigger: 'blur' }
        ]
      },
      sexOptions: []
    }
  },
  created() {
    this.queryDeptParams.schedulingDay = this.formatDate(new Date()); // 设置默认日期为今天
    this.initializeData();
    this.loadSex();
    this.loaduser()
    this.setSubsectionTypeBasedOnTime(); // 根据当前时间设置默认挂号时段
  },
  watch: {
    'patientParams.idCard': function(newVal) {
      if (newVal.length === 18) { // 假设身份证号是18位
        this.patientParams.sex = this.getSexFromIdCard(newVal);
        this.patientParams.birthday = this.getBirthdayFromIdCard(newVal);
        this.patientParams.age = this.calculateAgeFromId(newVal);
      }
    }
  },
  methods: {
    setSubsectionTypeBasedOnTime() {
      const now = new Date();
      const currentHour = now.getHours();

      if (currentHour < 12) {
        // 上午
        this.queryDeptParams.subsectionType = this.getSubsectionTypeByLabel('上午');
      } else if (currentHour >= 12 && currentHour < 18) {
        // 下午
        this.queryDeptParams.subsectionType = this.getSubsectionTypeByLabel('下午');
      } else {
        // 晚上
        this.queryDeptParams.subsectionType = this.getSubsectionTypeByLabel('晚上');
      }
    },
    getSubsectionTypeByLabel(label) {
      const subsection = this.subsectionTypeOptions.find(option => option.dictLabel === label);
      return subsection ? subsection.dictValue : null;
    },
    getSexFromIdCard(idCard) {
      const sexDigit = parseInt(idCard.substr(16, 1));
      return sexDigit % 2 === 0 ? '1' : '0'; // 偶数为女性，奇数为男性
    },
    getBirthdayFromIdCard(idCard) {
      const birthDate = idCard.substr(6, 8);
      return `${birthDate.substr(0, 4)}-${birthDate.substr(4, 2)}-${birthDate.substr(6, 2)}`;
    },
    calculateAgeFromId(idCard) {
      let birthday = this.getBirthdayFromIdCard(idCard);
      const birthDate = new Date(birthday);
      const nowDateTime = new Date();
      let age = nowDateTime.getFullYear() - birthDate.getFullYear();
      if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() === birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
        age--;
      }
      return age;
    },
    handleIdCardQuery() {
      this.$http.get("/doctor/registered/selectByCard/" + this.patientParams.idCard)
          .then(resp => {
            if (resp.data.code === 200 && resp.data.data) { // 确保数据非空
              this.patientParams = resp.data.data;
              this.patientParams.age = this.calculateAgeFromId(this.patientParams.idCard);
              this.isPatientLoaded = true;
              this.$message.success("加载成功");

            } else {
              this.$message.error(`没有该用户信息 请加载患者信息`);
              this.isPatientLoaded = false; // 加载失败，按钮不可用

            }
          })
          .catch(error => {
            this.$message.error(`请求错误: ${error}`);
            this.resetPatientParams(); // 发生错误时重置患者信息
          });
    },
    resetPatientParams() {
      this.patientParams = {
        idCard: this.patientParams.idCard, // 保留身份证号
        name: "",
        phone: "",
        sex: this.patientParams.sex,
        birthday: this.patientParams.birthday,
        age: this.patientParams.age,
        address: "",
      };
    },
    resetPatientParam() {
      this.patientParams = {
        idCard: "", // 保留身份证号
        name: "",
        phone: "",
        sex: "",
        birthday:"",
        age: "",
        address: "",
        patientId:null
      };
    },
    handleFullPatientInfo() {
      this.$refs.form.validate((valid) => {  // 首先进行表单验证
        if (valid) {
          this.$http.post("/doctor/registered/insert", this.patientParams)
              .then(resp => {
                if (resp.data.code === 200) {
                  this.patientParams.patientId=resp.data.data.patientId
                  this.isPatientLoaded = true;
                  this.$message.success("患者信息保存成功");
                } else {
                  this.isPatientLoaded = false;
                  this.$message.error(`保存失败: ${resp.data.message}`);
                }
              })
              .catch(error => {
                this.$message.error(`请求错误: ${error}`);
                this.isPatientLoaded = false;
              });
        } else {
          this.$message.error("请确保所有必填项已正确填写");
          this.isPatientLoaded = false;
        }
      });
    },
    loadSex() {
      this.$http.get("/system/dict/data/type/sys_user_sex")
          .then(resp => {
            this.sexOptions = resp.data.data;
          })
    },
    disablePastDates(date) {
      const today = new Date();
      // 将今天的日期部分设置为 00:00:00 以确保比较仅在日期部分进行
      today.setHours(0, 0, 0, 0);
      return date < today; // 禁用今天之前的日期
    },
    formatDate(date) {
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, '0');
      const d = String(date.getDate()).padStart(2, '0');
      return `${y}-${m}-${d}`;
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deptId);
      this.single = selection.length !== 1;
    },
    async initializeData() {
      await Promise.all([
        this.loadRegisteredItems(),
        this.loadDept(),
        this.loadSchedulingTypes(),
        this.loadSubsectionTypes(),

      ]);
    },
    async fetchApi(url, params, callback) {
      try {
        const resp = await this.$http.get(url, { params });
        callback(resp.data.data);
      } catch (error) {
        this.$message.error(`请求失败: ${error}`);
      }
    },
    loadRegisteredItems() {
      this.fetchApi("/doctor/registereditem/selectAll", null, data => {
        this.regItemOptions = data;
        if (data.length > 0) {
          this.queryDeptParams.regItemId = data[0].regItemId;
          this.queryDeptParams.regItemAmount = data[0].regItemFee;
        }
      });
    },
    loadDept() {
      this.fetchApi("/system/dept/list", null, data => {
        this.deptOptions = data;
      });
    },
    loadSchedulingTypes() {
      this.fetchApi("/system/dict/data/type/his_scheduling_type", null, data => {
        this.schedulingTypeOptions = data;
        // 如果加载的选项中存在值为 '1' 的选项，设置默认的 schedulingType 为其值
        const defaultType = this.schedulingTypeOptions.find(option => option.dictValue === '1');
        if (defaultType) {
          this.queryDeptParams.schedulingType = defaultType.dictValue; // 设置为 '1'
        }
      });
    },
    loadSubsectionTypes() {
      this.fetchApi("/system/dict/data/type/his_subsection_type", null, data => {
        this.subsectionTypeOptions = data;
        this.setSubsectionTypeBasedOnTime();
      });
    },

    handleDeptQuery() {
      this.loading = true;
      const params = {
        deptId: this.queryDeptParams.deptId,
        schedulingType: this.queryDeptParams.schedulingType,
        subsectionType: this.queryDeptParams.subsectionType,
        schedulingDay: this.queryDeptParams.schedulingDay
      };
      this.fetchApi("/doctor/scheduling/selectAll", params, data => {
        this.deptTableList = data;
        this.loading = false;
      });
    },
    registeredItemChange(value) {
      const selectedOption = this.regItemOptions.find(item => item.regItemId === value);
      if (selectedOption) {
        this.queryDeptParams.regItemAmount = selectedOption.regItemFee;

        // 根据 regItemId 设置 schedulingType
        if (value === 1 || value === 2) {
          this.queryDeptParams.schedulingType = '1'; // 设置为 '1' 门诊
        } else if (value === 3 || value === 4) {
          this.queryDeptParams.schedulingType = '2'; // 设置为 '2' 急诊
        } else {
          this.queryDeptParams.schedulingType = null; // 其他情况清空选择
        }
      }
    },

    generateRegistrationId() {
      const prefix = "GH";
      const timestamp = Date.now();  // 获取当前时间戳，等同于 Java 中的 System.currentTimeMillis()
      const randomNumber = Math.floor(Math.random() * 1000000);  // 生成一个随机数
      const formattedNumber = String(randomNumber).padStart(6, '0');  // 格式化随机数为六位数，不足前面补零
      return prefix + timestamp + formattedNumber;
    },
    handleRegistration() {
      const tx = this;
      // 验证收费科室、挂号类型、挂号时段、挂号时间是否为空
      if (!tx.queryDeptParams.deptId) {
        tx.$message.error("请选择收费科室");
        return;
      }
      if (!tx.queryDeptParams.schedulingType) {
        tx.$message.error("请选择挂号类型");
        return;
      }
      if (!tx.queryDeptParams.subsectionType) {
        tx.$message.error("请选择挂号时段");
        return;
      }
      if (!tx.queryDeptParams.schedulingDay) {
        tx.$message.error("请选择挂号时间");
        return;
      }
      const selectedDept = tx.deptTableList.find(dept => dept.deptId === tx.ids[0]);
      if (!selectedDept) {
        tx.$message.error("请先选择一个科室");
        return;
      }
      const currentNumber = selectedDept.currentNumber;
      const userId = selectedDept.userId;
      const username = selectedDept.user.userName;
      const createBy=this.userList.userName;
      tx.$refs['form'].validate(valid => {
        if (valid) {
          tx.$confirm('是否确认给【' + tx.patientParams.name + '】进行挂号?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            closeOnClickModal: false,
            type: 'warning',
            center: true
          }).then(() => {
            const deptId = tx.ids[0];
            const data = {
              registrationId: tx.generateRegistrationId(),
              patientId: tx.patientParams.patientId,
              patientName: tx.patientParams.name,
              userId: userId,
              doctorName: username,
              deptId: deptId,
              registrationItemId: tx.queryDeptParams.regItemId,
              registrationAmount: tx.queryDeptParams.regItemAmount,
              registrationNumber: currentNumber,
              registrationStatus: "0",
              visitDate: tx.queryDeptParams.schedulingDay,
              schedulingType: tx.queryDeptParams.schedulingType,
              subsectionType: tx.queryDeptParams.subsectionType,
              createBy:createBy,

            }
            console.log(data);
            // 使用POST方法提交数据到后台
            this.$http.post("/doctor/registration/insert", data)
                .then(response => {
                  const regId = response.data.data.registrationId;
                  tx.$message.success('挂号成功 挂号单号为【' + regId + '】');

                  tx.$confirm('是否确认给挂号ID为【' + regId + '】的挂号收费?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    closeOnClickModal: false,
                    type: 'warning',
                    center: true
                  }).then(() => {
                    tx.collectFee(regId); // 直接传递 regId
                  }).catch(() => {
                    tx.$message.error('收费取消');
                  });
                }).catch(() => {
              tx.$message.error('挂号失败');
            });
          }).catch(() => {
            tx.$message.error('挂号已取消');
          });
        }
      });
    },
    collectFee(registrationId) {
      this.$http.put("doctor/registration/updateStatus", { registrationId, registrationStatus: "1" })
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('收费成功');
              this.resetForm(); // 清空表单
              this.handleDeptQuery; // 刷新科室列表
            } else {
              this.$message.error(`收费失败: ${response.data.message}`);
            }
          })
          .catch(error => {
            this.$message.error(`请求错误: ${error}`);
          });
    },
    deptFormatter(row) {
      const dept = this.deptOptions.find(d => d.deptId === row.deptId);
      return dept ? dept.deptName : '未知';
    },
    resetForm() {
      // 只重置相关字段
      this.queryDeptParams.deptId = null;

      // 保持其他属性为默认值
      this.queryDeptParams.schedulingType = this.queryDeptParams.schedulingType || 1;
      this.queryDeptParams.subsectionType = this.queryDeptParams.subsectionType || this.getSubsectionTypeByLabel('上午');
      this.queryDeptParams.schedulingDay = this.queryDeptParams.schedulingDay || this.formatDate(new Date());

      // 清空科室列表
      this.deptTableList = [];
      this.patientParams={};
    }
    ,
    loaduser(){
      this.$http.get("/system/user/info").then(resp=>{
        this.userList = resp.data.data;
      })
    },
  }
}
</script>
